<script lang="ts" setup>
import type { SysDept } from '#/api/user/sysdept';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { addDept, editDept } from '#/api/user/sysdept';
import { $t } from '#/locales';

import { formSchema } from '../data';

const emit = defineEmits(['success']);

const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  schema: formSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    const data = (await formApi.getValues()) as SysDept;

    try {
      await (data?.deptId ? editDept(data) : addDept(data));
      modalApi.close();
      emit('success');
    } finally {
      modalApi.lock(false);
    }
  },
  onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData<SysDept>();
    modalApi.setState({
      title: data.deptId
        ? $t('ui.actionTitle.edit', [$t('dept.dept')])
        : $t('ui.actionTitle.create', [$t('dept.dept')]),
    });
    if (data) {
      if (data.parentId === 0) {
        data.parentId = null;
      }
      formApi.setValues(data, false);
    }
  },
});
</script>

<template>
  <Modal>
    <Form class="mx-4" />
  </Modal>
</template>
